package com.example.device.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.device.dto.DeviceUpdateRequest;
import com.example.device.dto.UpdateCheckResult;
import com.example.device.entity.DeviceConfig;
import com.example.device.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    public UpdateCheckResult checkBeforeUpdate(DeviceUpdateRequest request) {
        List<String> warnings = new ArrayList<>();
        DeviceConfig current = deviceMapper.selectById(request.getDeviceId());

        if (affectsRunningTasks(request)) {
            warnings.add("该配置将影响运行中的任务！");
        }
        if (willRestartDevice(request)) {
            warnings.add("设备将重启！");
        }

        return new UpdateCheckResult(!warnings.isEmpty(), warnings, current.getVersion());
    }

    public void performUpdate(DeviceUpdateRequest request) {
        DeviceConfig update = new DeviceConfig();
        update.setId(request.getDeviceId());
        update.setConfigJson(request.getNewConfig().toString());
        update.setVersion(request.getVersion());

        boolean success = deviceMapper.updateById(update) > 0;
        if (!success) {
            throw new RuntimeException("更新失败，数据已被修改，请刷新后重试！");
        }
    }

    // 分页查询设备列表
    public Page<DeviceConfig> getDevicePage(long page, long size) {
        Page<DeviceConfig> devicePage = new Page<>(page, size);
        return deviceMapper.selectPage(devicePage, null);
    }

    private boolean affectsRunningTasks(DeviceUpdateRequest r) {
        return true;
    }

    private boolean willRestartDevice(DeviceUpdateRequest r) {
        return true;
    }
}